package com.wellsoft.mobileoa.utils.widget;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;

import com.wellsoft.mobileoa.R;
import com.wellsoft.mobileoa.utils.BaseActivity;
import com.wellsoft.mobileoa.utils.BaseView;
import com.wellsoft.mobileoa.utils.BaseWidget;
import com.wellsoft.mobileoa.utils.SystemConfig;
import com.wellsoft.mobileoa.wsmodel.WSOA_DownloadFile_Request;
import com.wellsoft.mobileoa.wsmodel.WSOA_DownloadFile_Response;
import com.wellsoft.mobileoa.wsmodel.WSOA_PageField;
import com.wellsoft.mobileoa.wsmodel.WSOA_PageFieldButton;
import com.wmobile.utils.BaseObject;
import com.wmobile.utils.ServiceResponse;

public class FileWidget extends BaseWidget {
	private TextView fieldTitleTv;
	private Button fieldValueBtn;

	public FileWidget(WSOA_PageField field, BaseView baseView) {
		this.field = field;
		this.baseView = baseView;
	}

	@Override
	public View getView() {
		view = LayoutInflater.from(baseView.getBaseActivity()).inflate(R.layout.filewidget,
				null);
		fieldTitleTv = (TextView) view
				.findViewById(R.id.filewidget_fieldtitletv);
		fieldTitleTv.setText(field.getFieldTitle());
		fieldValueBtn = (Button) view
				.findViewById(R.id.filewidget_fieldvaluebtn);
		fieldValueBtn.setText(field.getFieldValue());
		fieldValueBtn.setOnClickListener(onFileOpenListener);
		fieldValueBtn.setOnTouchListener(onIconTouchListener);
		return view;
	}
	
	OnTouchListener onIconTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			Button btn = (Button)v;
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				btn.setBackgroundColor(Color.argb(255, 239, 239, 239));
			} else if (event.getAction() == MotionEvent.ACTION_UP) {
				btn.setBackgroundColor(Color.argb(255, 255, 255, 255));
			} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
				btn.setBackgroundColor(Color.argb(255, 255, 255, 255));
			} else if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
				btn.setBackgroundColor(Color.argb(255, 255, 255, 255));
			}
			return false;
		}
	};

	OnClickListener onFileOpenListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			File file = null;
			String fileType = ".pdf|.txt|.xls|.xlsx|.doc|.docx|.jpg|.jpeg|.gif|.html|.htm|.bmp|.png|.ppt|.pptx";
			String[] fileTypes = fileType.split("\\|");
			boolean isSupported = false;

			for (String type : fileTypes) {
				if (field.getFieldValue().toLowerCase().indexOf(type) > -1) {
					isSupported = true;
					break;
				}
			}
			if (!isSupported) {
				baseView.getBaseActivity().showMessage("不支持的文件类型！");
				return;
			}
			AlertDialog alertDialog = baseView.getBaseActivity().showWaitingDialog();
			WSOA_PageFieldButton button = field.getFieldButtons().get(0);

			WSOA_DownloadFile_Request request = new WSOA_DownloadFile_Request();
			request.setUrl(button.getAction().getUrl());
			request.setCookies(SystemConfig.getCookies());

			Map<String, BaseObject> httpRequests = new HashMap<String, BaseObject>();

			httpRequests.put("request", request);
			ServiceResponse httpGetResponse = SystemConfig.getService()
					.Callservice(httpRequests, "WSOA_DownloadFile",
							WSOA_DownloadFile_Response.class);
			if (!httpGetResponse.getExeFlag()) {
				alertDialog.dismiss();
				baseView.getBaseActivity().showMessage(httpGetResponse.getMessage());
				return;
			}
			WSOA_DownloadFile_Response response = (WSOA_DownloadFile_Response) httpGetResponse
					.getResponseData();
			if (response.getExeFlag() == 0) {
				alertDialog.dismiss();
				baseView.getBaseActivity().showMessage(response.getMessage());
				return;
			}
			if (response.getExeFlag() == 2) {
				if (SystemConfig.reLogin()) {
					onFileOpenListener.onClick(v);
					return;
				} else {
					BaseActivity.returnLoginActivity();
					return;
				}
			}
			try{
				file = saveToSdCard(field.getFieldValue(), response.getFileContent());
			}catch(Exception e){
				alertDialog.dismiss();
				baseView.getBaseActivity().showMessage("文件保存失败！");
				return;
			}
			alertDialog.dismiss();
			try{
				Intent intent = openFile(file);
				baseView.getBaseActivity().NewActivity(intent);
			}catch(Exception e){
				baseView.getBaseActivity().showMessage("不支持的文件类型！");
				return;
			}
		}
	};

	// 保存文件到SD卡
	public File saveToSdCard(String filename, byte[] fileContent)
			throws IOException {
		// 得到手机默认存储目录。并实例化
		File file = new File(Environment.getExternalStorageDirectory(),
				filename);
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(fileContent);
		fos.close();
		return file;
	}

	public static Intent openFile(File file) {

		/* 取得扩展名 */
		String end = file
				.getName()
				.substring(file.getName().lastIndexOf(".") + 1,
						file.getName().length()).toLowerCase();
		/* 依扩展名的类型决定MimeType */
		if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
				|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
			return getAudioFileIntent(file.getAbsolutePath());
		} else if (end.equals("3gp") || end.equals("mp4")) {
			return getAudioFileIntent(file.getAbsolutePath());
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			return getImageFileIntent(file.getAbsolutePath());
		} else if (end.equals("apk")) {
			return getApkFileIntent(file.getAbsolutePath());
		} else if (end.equals("ppt")) {
			return getPptFileIntent(file.getAbsolutePath());
		} else if (end.equals("pptx")) {
			return getPptFileIntent(file.getAbsolutePath());
		} else if (end.equals("xls")) {
			return getExcelFileIntent(file.getAbsolutePath());
		} else if (end.equals("xlsx")) {
			return getExcelFileIntent(file.getAbsolutePath());
		} else if (end.equals("doc")) {
			return getWordFileIntent(file.getAbsolutePath());
		} else if (end.equals("docx")) {
			return getWordFileIntent(file.getAbsolutePath());
		} else if (end.equals("pdf")) {
			return getPdfFileIntent(file.getAbsolutePath());
		} else if (end.equals("chm")) {
			return getChmFileIntent(file.getAbsolutePath());
		} else if (end.equals("txt")) {
			return getTextFileIntent(file.getAbsolutePath(), false);
		} else {
			return getAllIntent(file.getAbsolutePath());
		}
	}

	// Android获取一个用于打开APK文件的intent
	public static Intent getAllIntent(String param) {

		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "*/*");
		return intent;
	}

	// Android获取一个用于打开APK文件的intent
	public static Intent getApkFileIntent(String param) {

		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		return intent;
	}

	// Android获取一个用于打开VIDEO文件的intent
	public static Intent getVideoFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("oneshot", 0);
		intent.putExtra("configchange", 0);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "video/*");
		return intent;
	}

	// Android获取一个用于打开AUDIO文件的intent
	public static Intent getAudioFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("oneshot", 0);
		intent.putExtra("configchange", 0);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "audio/*");
		return intent;
	}

	// Android获取一个用于打开Html文件的intent
	public static Intent getHtmlFileIntent(String param) {

		Uri uri = Uri.parse(param).buildUpon()
				.encodedAuthority("com.android.htmlfileprovider")
				.scheme("content").encodedPath(param).build();
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.setDataAndType(uri, "text/html");
		return intent;
	}

	// Android获取一个用于打开图片文件的intent
	public static Intent getImageFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "image/*");
		return intent;
	}

	// Android获取一个用于打开PPT文件的intent
	public static Intent getPptFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
		return intent;
	}

	// Android获取一个用于打开Excel文件的intent
	public static Intent getExcelFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/vnd.ms-excel");
		return intent;
	}

	// Android获取一个用于打开Word文件的intent
	public static Intent getWordFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/msword");
		return intent;
	}

	// Android获取一个用于打开CHM文件的intent
	public static Intent getChmFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/x-chm");
		return intent;
	}

	// Android获取一个用于打开文本文件的intent
	public static Intent getTextFileIntent(String param, boolean paramBoolean) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		if (paramBoolean) {
			Uri uri1 = Uri.parse(param);
			intent.setDataAndType(uri1, "text/plain");
		} else {
			Uri uri2 = Uri.fromFile(new File(param));
			intent.setDataAndType(uri2, "text/plain");
		}
		return intent;
	}

	// Android获取一个用于打开PDF文件的intent
	public static Intent getPdfFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/pdf");
		return intent;
	}

}
